package com.youpai.platform.user.service.handler;

import com.alibaba.fastjson.JSONObject;
import com.youpai.platform.common.entity.resp.BaseResponse;
import com.youpai.platform.common.enums.ProcessCodeEnum;
import com.youpai.platform.common.util.DeviceContext;
import com.youpai.platform.common.util.UserContext;
import com.youpai.platform.common.util.cache.Cache;
import com.youpai.platform.user.web.entity.dto.UserDTO;
import com.youpai.platform.user.service.entity.po.UserPO;
import com.youpai.platform.user.service.converter.UserConverter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @date: 2021/11/29 22:55
 * @author: Anna
 * @version: 1.0
 * @description: 用户信息处理handler
 */
@Component
public class UserInfoHandler implements HandlerInterceptor {

    @Resource
    @Qualifier(value = "redisCache")
    private Cache<String, Long> tokenCache;
    @Resource
    @Qualifier(value = "redisCache")
    private Cache<Long, UserPO> userCache;

    private static final boolean CHECK_TOKEN = false;

    private final String[] excludes = new String[]{"/user/login", "/user/register",
            "/user/login/phone", "/user/verification-code/send", ".js", "doc.html", ".css", "/vulture/handshake/token"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("w-token");
        String appId = request.getHeader("app-id");
        if (StringUtils.isNotBlank(appId)) {
            DeviceContext.setAppId(Integer.parseInt(appId));
        }
        // token 是否为空
        if (StringUtils.isBlank(token)) {
            // 清除环境值
            UserContext.cleanUserContext();
            // 判断是否开启验证
            if (!CHECK_TOKEN) {
                return true;
            }
            String requestURI = request.getRequestURI();
            for (String exclude : excludes) {
                if (requestURI.contains(exclude)) {
                    return true;
                }
            }
        } else {
            Long uid = tokenCache.getValue(token, Long.class);
            if (null != uid) {
                UserPO userPO = userCache.getValue(uid, UserPO.class);
                if (null != userPO) {
                    UserDTO userDTO = UserConverter.convertUserPO2UserDTO(userPO);
                    UserContext.setUserContext(userDTO);
                    response.setHeader("w-token", token);
                } else
                    response.setHeader("w-token", "");
                return true;
            }
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        try {
            response.getWriter().print(JSONObject.toJSON(BaseResponse.fail(ProcessCodeEnum.TOKEN_FAILURE)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }
}
